package org.example.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.pojo.User;
import org.example.service.OrderService;

import java.io.IOException;

@WebServlet("/orders")
public class OrderServlet extends HttpServlet {
    private final OrderService orderService = new OrderService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        User currentUser = (User) session.getAttribute("user");
        request.setAttribute("orders", orderService.getOrdersByUserId(currentUser.getId()));
        request.getRequestDispatcher("orders.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        String action = request.getParameter("action");

        if ("delete".equals(action)) {
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            boolean isDeleted = orderService.deleteOrderAndRestoreStock(orderId);
            if (isDeleted) {
                request.setAttribute("message", "订单删除成功，并已恢复库存！");
            } else {
                request.setAttribute("error", "订单删除失败！");
            }
        }

        response.sendRedirect(request.getContextPath() + "/orders");
    }
}
